﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Atomic.Common;
using Atomic.Common.Validators;
using System.Data.Common;
using System.Linq.Expressions;
using Atomic.Permission.Entities;
using NHibernate.Criterion;
using NHibernate.Linq;
using NHibernate;
using Atomic.Db;
using Atomic.Permission.DAL;

namespace Atomic.Permission.BLL
{
    public class FormBLL : ErrorImpl, IForm
    {
        #region 系统所有窗体

        /// <summary>
        /// 条件查询系统配置的窗体
        /// </summary>
        /// <param name="pager">分页参数，获取系统所有窗体，填入null</param>
        /// <param name="predicate">查询条件</param>
        /// <returns>分页的窗体结果</returns>
        public Pager<FormEntity> GetPager(Pager pager, Expression<Func<FormEntity, bool>> predicate = null)
        {
            FormDAL formDAL = new FormDAL();
            return formDAL.GetPager(pager, predicate);
        }

        /// <summary>
        /// 查询所有子窗体，按Sort属性排序
        /// </summary>
        /// <param name="parentId">父窗体ID</param>
        /// <returns>子窗体列表</returns>
        public virtual List<FormEntity> GetChildren(int parentId)
        {
            FormDAL formDAL = new FormDAL();
            List<FormEntity> list = formDAL.GetList(m => m.PID.Equals(parentId))    //子节点
                .OrderBy(m => m.Sort)   //排序
                .ToList();
            return list;
        }

        /// <summary>
        /// 添加新的窗体，如果新窗体有父窗体，则父窗体的子窗体记录数字段增加
        /// </summary>
        /// <param name="entity">新窗体</param>
        /// <returns>添加窗体是否成功</returns>
        public virtual bool Add(FormEntity entity)
        {
            //实体验证
            if (!(VResult = entity.Validate()).Success)
            {
                Error = new ErrorResult()
                {
                    Message = VResult.FailureMessage
                };
                return false;
            }

            using (ISession session = HibernateHelper.GetSession())
            {
                FormDAL formDAL = new FormDAL(session);
                session.BeginTransaction();
                try
                {
                    formDAL.Add(entity);    //添加新窗体
                    //是否具备父窗体
                    if (entity.PID > 0)
                    {
                        FormEntity parent = formDAL.Get(entity.PID);    //获取父窗体对象
                        if (parent == null)
                        {
                            Error = new ErrorResult()
                            {
                                Message = "找不到指定的父窗体"
                            };
                            session.Transaction.Rollback();
                            return false;
                        }
                        parent.ChildrenCount += 1;  //子节点+1
                    }
                    session.Transaction.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    session.Transaction.Rollback();
                    throw new Exception("增加新窗体引发异常", ex);
                }
            }
        }

        /// <summary>
        /// 更新窗体信息，不包括ChildrenCount
        /// </summary>
        /// <param name="entity">窗体信息</param>
        /// <param name="id">要更新窗体的主键</param>
        /// <returns>更新是否成功</returns>
        public virtual bool Update(FormEntity entity, int id)
        {
            FormDAL formDAL = new FormDAL();
            formDAL.Update(entity, id);
            return true;
        }

        /// <summary>
        /// 删除窗体：
        /// 1.删除前，有子窗体则禁止删除；
        /// 2.删除子窗体，更新父窗体的子窗体计数器；
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns>窗体删除是否成功</returns>
        public virtual bool Remove(int id)
        {
            using (ISession session = HibernateHelper.GetSession())
            {
                FormDAL formDAL = new FormDAL(session);

                //有子节点，则禁止删除
                if (formDAL.Exist(m => m.PID == id))
                {
                    Error = new ErrorResult()
                    {
                        Message = "子窗体不为空，请先删除子窗体。"
                    };
                    return false;
                }
                
                //要删除的窗体
                FormEntity form = session.Get<FormEntity>(id);
                if (form == null)
                {
                    Error = new ErrorResult()
                    {
                        Message = "找不到要删除的窗体。"
                    };
                    return false;
                }

                //开启删除事务
                session.BeginTransaction();
                try
                {
                    //更新要删除窗体的父窗体
                    FormEntity parent = session.Get<FormEntity>(form.PID);
                    if (parent == null)
                    {
                        Error = new ErrorResult()
                        {
                            Message = "找不到要删除的窗体的父窗体。"
                        };
                        return false;
                    }
                    parent.ChildrenCount -= 1;  //更新子窗体数
                    formDAL.Remove(form.ID);    //删除窗体

                    //提交事务
                    session.Transaction.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    session.Transaction.Rollback();
                    throw new Exception("删除窗体引发异常", ex);
                }
            }
        }

        public FormEntity Get(int id)
        {
            FormDAL formDAL = new FormDAL();
            return formDAL.Get(id);
        }
        #endregion



    }
}